<?php
namespace App\Admin\Controllers;
use App\Admin\Models\ArticleCategories;
use App\Admin\Models\ArticleFaquan;
use App\Admin\Models\ArticleFaquanCate;
use App\Admin\Models\Articles;
use Common\ControllerAdBase;

use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Paginator\Adapter\NativeArray as PaginatorArray;

class GoodsController extends ControllerAdBase
{
    //好单库商品分类
    public $classify = [
        '1'  => '女装',
        '2'  => '男装',
        '3'  => '内衣',
        '4'  => '美妆',
        '5'  => '配饰',
        '6'  => '鞋品',
        '7'  => '箱包',
        '8'  => '儿童',
        '9'  => '母婴',
        '10' => '居家',
        '11' => '美食',
        '12' => '数码',
        '13' => '家电',
        '14' => '其他',
        '15' => '车品',
        '16' => '文体',
        '17' => '宠物'
    ];

    public function initialize()
    {
        parent::initialize();
    }

    public function articlelistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        if (isset($this->params['cateid'])) {
            $data['cateid'] = $this->params['cateid'];
        }
        if (isset($this->params['keywords'])) {
            $data['keywords'] = $this->params['keywords'];
        }
        $article    = new Articles();
        $list       = $article->article_list($data);
        $paginator  = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items = $paginator->getPaginate();
        $list_items = ToolsController::paging($list_items);
        foreach ($list_items['items'] as $key => $value) {
            $cate_article                           = new ArticleCategories();
            $cate_arr                               = $cate_article->find_first_by_Id($value['article_category_id']);
            $list_items['items'][$key]['cate_name'] = $cate_arr ? $cate_arr['name'] : '分类未找到';
            $list_items['items'][$key]['images']    = explode(',', $value['images']);
        }
        $this->ok($list_items);
    }


    /**
     * 获取分类
     */
    public function getCateAction()
    {
        $article_cate = new ArticleCategories();
        $catelist     = $article_cate->getlist();
        $this->ok($catelist);
    }


    //分类列表
    public function catelistAction()
    {
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $article_cate = new ArticleCategories();
        $catelist     = $article_cate->getlist();
        $paginator    = new PaginatorModel(
            array(
                "data"  => $catelist,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items   = $paginator->getPaginate();
        $this->ok($list_items);
    }


    public function addgoodsAction()
    {
        $this->validata_filed($this->params);
        $goods_arr = $this->haodanku->goods_detail($this->params['goods_id']);
        if(!$goods_arr){
            $this->fail(-1,'该商品非淘客商品或已下架');
        }
        $goods_detail        = new Freegoods();
        $goods_detail->goods_id        = $this->params['goods_id'];
        $goods_detail->site            = $this->params['site'];
        $goods_detail->title           = $goods_arr['Title'];
        $goods_detail->pic             = $goods_arr['PicLogo'];
        $goods_detail->free_price       = $this->params['free_price'];
        $goods_detail->counts       = $this->params['red_count'];
        $goods_detail->buyed       = $this->params['red_count'] - $this->params['red_buyed'];
        $goods_detail->less       = $this->params['red_buyed'];
        $goods_detail->coupon          = $goods_arr['CouponMoney'];
        $goods_detail->price           = $goods_arr['EndPrice'];
        $goods_detail->commission      = $goods_arr['Commission'];
        $goods_detail->old_price       = $goods_arr['Price'];
        $goods_detail->status          = $this->params['status'];
        $goods_detail->send_start_time = $this->params['send_start_time'];
        $goods_detail->send_end_time = $this->params['send_end_time'];
        $goods_detail->updated_at      = date('Y-m-d H:i:s', time());
        $goods_detail->update_at      = date('Y-m-d H:i:s', time());
        $goods_detail->types           =  'free';
        if ($goods_detail->save()) {
            $this->ok([]);
        } else {
            $this->fail(-1, '添加失败');
        }
    }


    public function updategoodsAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $this->validata_filed($this->params);
        $goods        = new Freegoods();
        $goods_detail = $goods->findFirstById($this->params['id']);
        if (!$goods_detail) {
            $this->fail(-1, '该商品不存在或以被删除');
        }
        $goods_detail->goods_id        = $this->params['goods_id'];
        $goods_detail->site            = $this->params['site'];
        $goods_detail->type           = ($this->params['types'] == 1) ? 'yiyuan' : 'free';
        $goods_detail->title           = $this->params['title'];
        $goods_detail->pic             = $this->params['pic'];
        $goods_detail->free_price       = $this->params['free_price'];
        $goods_detail->counts       = $this->params['red_count'];
        $goods_detail->buyed       = $this->params['red_count'] - $this->params['red_buyed'];
        $goods_detail->less       = $this->params['red_buyed'];
        $goods_detail->coupon          = $this->params['coupon'];
        $goods_detail->price           = $this->params['price'];
        $goods_detail->old_price       = $this->params['old_price'];
        $goods_detail->status          = $this->params['status'];
        $goods_detail->send_start_time = $this->params['send_start_time'];
        $goods_detail->send_end_time = $this->params['send_end_time'];
        $goods_detail->update_at      = date('Y-m-d H:i:s', time());
        if ($goods_detail->save()) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }


    private function validata_filed($params)
    {
        if (empty($params['goods_id'])) {
            $this->fail(-1, '商品id不能为空');
        }
        /**
        if (empty($params['title'])) {
            $this->fail(-1, '商品标题不能为空');
        }
        if (empty($params['pic'])) {
            $this->fail(-1, '商品图片不能为空');
        }
        if (empty($params['free_price'])) {
            $this->fail(-1, '原价不能为空');
        }
         * */
//        if (empty($params['red_price'])) {
//            $this->fail(-1, '红包金额不能为空');
//        }
        if (empty($params['red_count'])) {
            $this->fail(-1, '红包个数不能为空');
        }
        if (empty($params['red_buyed'])) {
            $this->fail(-1, '红包剩余个数不能为空');
        }
        /*
        if (empty($params['coupon'])) {
            $this->fail(-1, '优惠卷不能为空');
        }
        if (empty($params['price'])) {
            $this->fail(-1, '价格不能为空');
        }
        if (empty($params['old_price'])) {
            $this->fail(-1, '原价不能为空');
        }
        */
        if (empty($params['send_start_time'])) {
            $this->fail(-1, '开始时间不能为空');
        }
        if (empty($params['send_end_time'])) {
            $this->fail(-1, '开始时间不能为空');
        }

        if($params['red_count']<$params['red_buyed']){
            $this->fail(-1,'剩余红包个数不能大于总红包个数');
        }
    }


    /**
     * 查看
     */
    public function detailgoodsAction()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            $this->fail(-1, '商品id不能为空');
        }
        $goods = new Freegoods();
        $list  = $goods->goods_detail($id);
        $this->ok($list);
    }

    public function delfreeAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $version        = new Version();
        $notices_detail = $version->findFirstById($this->params['id']);
        if (empty($notices_detail)) {
            $this->fail(-1, '版本不存在，或已被删除');
        }
        $result = $notices_detail->delete();
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '删除失败');
        }
    }


    //*************************************************************爆品优选栏目列表*************************************************************************************************************
    public function blistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $bfaquanlist = new ArticleFaquanCate();
        $list        = $bfaquanlist->find_list($this->params);
        $paginator   = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items  = $paginator->getPaginate();
        $this->ok($list_items);
    }

    public function baddAction()
    {
        $this->validate_faquanfield($this->params);
        $faquancate         = new ArticleFaquanCate();
        $info['created_at'] = date('Y-m-d H:i:s', time());
        $info['name']       = $this->params['name'];
        $info['sort']       = $this->params['sort'];
        $info['is_show']    = $this->params['is_show'];
        $info['updated_at'] = date('Y-m-d H:i:s', time());
        $result             = $faquancate->save_params($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    public function bupdateAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $faquancate = new ArticleFaquanCate();
        $info       = $faquancate->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该栏目不存在或已被删除');
        }
        $info['name']       = $this->params['name'];
        $info['sort']       = $this->params['sort'];
        $info['is_show']    = $this->params['is_show'];
        $info['updated_at'] = date('Y-m-d H:i:s', time());
        $result             = $faquancate->save_params($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    private function validate_faquanfield($params)
    {
        if (!isset($params['name']) || empty($params['name'])) {
            $this->fail(-1, '栏目标题不能为空');
        }
        if (!isset($params['sort']) || empty($params['sort'])) {
            $this->fail(-1, '排序不能为空');
        }
    }

    public function bdelAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $faquanDb = new ArticleFaquan();
        $faquan = $faquanDb->find_count($this->params['id']);
        if($faquan){
            $this->fail(-1,'请删除爆品优选下面的商品');
        }
        $faquan_cateDb = new ArticleFaquanCate();
        $faquancate = $faquan_cateDb->findFirstById($this->params['id']);
        if($faquancate->delete()){
            $this->ok([]);
        }
        $this->fail(-1,'删除失败');

    }


    //*************************************************************爆品优选内容列表*************************************************************************************************************
    public function glistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $faquan     = new ArticleFaquan();
        $list       = $faquan->find_list($this->params);
        $paginator  = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items = $paginator->getPaginate();
        $list_items = ToolsController::paging($list_items);
        foreach ($list_items['items'] as $key => $value) {
            $faquancate = new ArticleFaquanCate();
            $info       = $faquancate->find_by_id($value['cateid']);
            $list_items['items'][$key]['content'] = base64_decode($value['content']);
            $list_items['items'][$key]['catename'] = $info ? $info['name'] : '';
            $list_items['items'][$key]['itempic']  = $value['itempic'] ? explode(',', $value['itempic']) : '';
        }
        $this->ok($list_items);
    }


    public function gupdateAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '内容id不能为空');
        }
        if (!isset($this->params['itempic']) || empty($this->params['itempic'])) {
            $this->fail(-1, '缺少封面图');
        }
        $faquan = new ArticleFaquan();
        $info   = $faquan->find_first_by_Id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该该内容不存在或已被删除');
        }
        $this->gvalidate_file($this->params);
        $info['cateid']   = $this->params['cateid'];
        $info['content']  = base64_encode($this->params['content']);
        $info['itemid']   = $this->params['itemid'];
        $info['nickname'] = $this->params['nickname'];
        $info['avatar']   = $this->params['avatar'];
        $info['video_url']   = $this->params['video_url'];
        $info['video_cover']   = $this->params['video_cover'];
        $faquan           = new ArticleFaquan();
        $result           = $faquan->save_params($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }


    public function gaddAction()
    {
        $this->gvalidate_file($this->params);
        $goods_info = $this->haodanku->goods_detail($this->params['itemid']);
        if(!$goods_info){
            $this->fail(-1,'没有找到商品');
        }
        $info['cateid']   = $this->params['cateid'];
        $info['content']  = base64_encode($this->params['content']);
        $info['itemid']   = $this->params['itemid'];
        $info['nickname'] = $this->params['nickname'];
        $info['avatar']   = $this->params['avatar'];
        $info['video_cover']   = $this->params['video_cover'];

        $info['created_at']   = date('Y-m-d H:i:s');
        $info['itempic']  = $goods_info['SmallImages'] ? implode(',', $goods_info['SmallImages']) : implode(',', $goods_info['PicList']);
        $info['title']   = $goods_info['Title'];
        $info['commission']   = $goods_info['Commission'];
        $info['shop_type']   = $goods_info['ShopType'];
        $info['price']   = $goods_info['Price'];
        $info['end_price']   = $goods_info['EndPrice'];
        $info['piclogo']   = $goods_info['PicLogo'];
        $info['month_sale']   = $goods_info['MonthSale'];
        $faquan           = new ArticleFaquan();
        $result           = $faquan->save_params($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '添加失败');
        }
    }


    private function gvalidate_file($params)
    {
        if (!isset($params['cateid']) || empty($params['cateid'])) {
            $this->fail(-1, '分类不能为空');
        }
        if (!isset($params['content']) || empty($params['content'])) {
            $this->fail(-1, '推荐内容不能为空');
        }
        if (!isset($params['itemid']) || empty($params['itemid'])) {
            $this->fail(-1, '商品id不能为空');
        }
    }

    public function gdelAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '内容id不能为空');
        }
        $faquan = new ArticleFaquan();
        $result = $faquan->findFirstById($this->params['id'])->delete();
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '删除失败');
        }
    }

    public function gdetailAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '内容id不能为空');
        }
        $faquan          = new ArticleFaquan();
        $info            = $faquan->find_first_by_Id($this->params['id']);
        $info['content'] = base64_decode($info['content']);
        if (empty($info)) {
            $this->fail(-1, '该该内容不存在或已被删除');
        }
        $this->ok($info);
    }


    /**
     * 发圈列表
     */
    public function fqlistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        $path = str_replace('public', "app/plugins/Haodanku.php", getcwd());
        require_once $path;
        $haodanku           = new Haodanku();
        $res                = $haodanku->faquan($page);
        $res['items']       = $res;
        $res['total_items'] = 1000;

        $this->ok($res);
    }


    /**
     * 发圈分类
     */
    public function gcateAction()
    {
        $faquan = new ArticleFaquanCate();
        $list   = $faquan->find_list();
        $this->ok($list);
    }


    /**
     * 发圈添加到库
     */
    public function fqaddAction()
    {
        $this->gvalidate_file($this->params);
        $articlefaquan = new ArticleFaquan();
        $count_itemid  = $articlefaquan->find_goods_itemsid($this->params['itemid']);
        if ($count_itemid) {
            $this->fail(-1, '对不起，该商品已经添加了,请先删除');
        }
        $pic_arr = [];
        foreach ($this->params['itempic'] as $key => $value) {
            if ($key <= 2) {
                $pic_arr[$key] = $value;
            }
        }
        $info['cateid']   = $this->params['cateid'];
        $info['content']  = base64_encode($this->params['content']);
        $info['itemid']   = $this->params['itemid'];
        $info['itempic']  = implode(',', $pic_arr);
        $info['nickname'] = $this->params['nickname'];
        $info['avatar']   = $this->params['avatar'];
        $faquan           = new ArticleFaquan();
        $result           = $faquan->save_params($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '添加失败');
        }
    }


    /**
     * 站内商品列表API开关
     */
    public function swAction()
    {
        $type  = isset($this->params['type']) ? intval($this->params['type']) : 3;
        $redis = $this->getRedis();
        $key   = 'Goods_list_api_switch';
        $res   = [];
        if ($type !== 3) { //设置
            $value = $type == 1 ? 1 : 0;
            $redis->set($key, $value);
        } else {//获取
            $value        = $redis->get($key);
            $res['value'] = empty($value) ? false : true;
        }

        $this->ok($res);
    }


    /**
     * 大淘客收藏商品导入
     */
    public function collegeAction()
    {

//        $redis = $this->redis;
//        $key   = 'Da_tao_ke_college_import';
//        $value = $redis->get($key);
//        if ($value) {
//            $this->fail(-1, '大淘客收藏商品正在导入,请稍后点击');
//        }
//        $redis->set($key, 1);
//        sleep(5);
        $category_id        = intval($this->params['category_id']);
        $category_second_id = intval($this->params['category_second_id']);
        $column_id          = strstr($this->params['column_id'], '_', true);
        $column_second_id   = strstr($this->params['column_second_id'], '_', true);
        /**
         * @see taoke::getCollectionAll
         */
        $collects = $this->taoke->getCollectionAll();
        $total    = count($collects);
        if (empty($collects)) {
            $this->fail(-1, '请先收藏大淘客的商品');
        }
        $goods       = new Goods();
        $ids         = implode(',', array_column($collects, 'goodsId'));
        $exist_count = $goods->goods_count_by(['item_id in (' . $ids . ')']);

        if ($total == $exist_count) {
            $this->fail(-1, '已导入，请不要重复导入', ['id' => $ids]);
        }
        foreach ($collects as $v) {
            $res = $this->taoke->getGoodsDetails($v, false);

            if ($res) {
                $goods                   = new Goods();
                $condition['conditions'] = 'item_id=' . $res['goodsId'];
                $exist                   = $goods->findFirst($condition);
                if ($exist) {
                    $goods->id         = $exist->id;
                    $goods->updated_at = date('Y-m-d H:i:s', time());
                    $goods->top        = $exist->top;
                    $goods->status     = $exist->status;
                    $goods->created_at = $exist->created_at;
                } else {
                    $goods->created_at = date('Y-m-d H:i:s', time());
                }
                $goods->item_id            = $res['goodsId'];
                $goods->category_id        = $category_id;
                $goods->category_second_id = $category_second_id;
                $goods->column_id          = $column_id;
                $goods->column_second_id   = $column_second_id;
                $goods->title              = $res['title'];
                $goods->short_title        = $res['dtitle'];
                $goods->shop_type          = $res["shopType"] == "B" ? "天猫" : "淘宝";
                $goods->pic_logo           = $res['mainPic'];
                $goods->coupon_money       = $res['couponPrice'];
                $goods->price              = $res['originalPrice'];
                $goods->end_price          = $res['actualPrice'];
                $goods->month_sale         = $res['monthSales'];
                $goods->shop_name          = $res['shopName'];
                $goods->commission         = $res['actualPrice'] * ($res['commissionRate'] / 100);
                $goods->coupon_surplus     = $res['couponTotalNum'] - $res['couponReceiveNum'];
                $goods->coupon_total       = $res['couponTotalNum'];

                $goods->site   = 'haodanku';
                $goods->status = 1;

//                if ($goods->save() === false) {
//                    echo "Umh, We can't store robots right now: \n";
//                    $messages = $goods->getMessages();
//                    foreach ($messages as $message) {
//                        echo $message, "\n";
//                    }
//                    exit;
//                }
                $goods->save();
            }
        }

        $this->ok(['total' => $total]);
    }

    /**
     * 好当库商品导入
     */
    public function importAction()
    {
        if (!isset($this->params['itemid']) || empty($this->params['itemid'])) {
            $this->fail(-1, '商品id不能为空');
        }
        $ids                = explode(',', trim($this->params['itemid']));
        $category_id        = intval($this->params['category_id']);
        $category_second_id = intval($this->params['category_second_id']);
        $column_id          = strstr($this->params['column_id'], '_', true);;
        $column_second_id = strstr($this->params['column_second_id'], '_', true);
        foreach ($ids as $id) {
            /**
             * @see Haodanku::h_goods_detail
             */
            $res = $this->haodanku->h_goods_detail($id);

            if ($res) {
                $goods                   = new Goods();
                $condition['conditions'] = "item_id=$id";
                $exist                   = $goods->findFirst($condition);
                if ($exist) {
                    $goods->id         = $exist->id;
                    $goods->updated_at = date('Y-m-d H:i:s', time());
                    $goods->top        = $exist->top;
                    $goods->status     = $exist->status;
                    $goods->created_at = $exist->created_at;
                } else {
                    $goods->created_at = date('Y-m-d H:i:s', time());
                }
                $goods->item_id            = $res['itemid'];
                $goods->category_id        = $category_id;
                $goods->category_second_id = $category_second_id;
                $goods->column_id          = $column_id;
                $goods->column_second_id   = $column_second_id;
                $goods->title              = $res['itemtitle'];
                $goods->short_title        = $res['itemshorttitle'];
                $goods->shop_type          = $res["shoptype"] == "B" ? "天猫" : "淘宝";
                $goods->pic_logo           = $res['itempic'];
                $goods->coupon_money       = $res['couponmoney'];
                $goods->price              = $res['itemprice'];
                $goods->end_price          = $res['itemendprice'];
                $goods->month_sale         = $res['itemsale'];
                $goods->shop_name          = $res['shopname'];
                $goods->commission         = $res['tkmoney'];
                $goods->coupon_surplus     = $res['couponsurplus'];
                $goods->coupon_total       = $res['couponnum'];

                $goods->site   = 'haodanku';
                $goods->status = 1;

//                if ($goods->save() === false) {
//                    echo "Umh, We can't store robots right now: \n";
//                    $messages = $goods->getMessages();
//                    foreach ($messages as $message) {
//                        echo $message, "\n";
//                    }
//                    exit;
//                }
                $goods->save();

            }

        }
        $this->ok([]);
    }

    /**
     * 好当库商品列表
     */
    public function drlistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = $this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        if (!isset($this->params['category_id']) || empty($this->params['category_id'])) {
            $categoryId = 0;
        } else {
            $categoryId = (int)$this->params['category_id'];
        }
        if (!isset($this->params['nav']) || empty($this->params['nav'])) {
            $nav = 1;
        } else {
            $nav = (int)$this->params['nav'];
        }

        $params = [
            'nav'         => $nav,
            'page'        => $page,
            'page_size'   => $pageSize,
            'category_id' => $categoryId,
            'order_by'    => isset($this->params['order_by']) ? $this->params['order_by'] : '',
        ];
        /**
         * @see Haodanku::goods_list
         * @see Haodanku::trun_list
         */
        $res   = $this->haodanku->goods_list($params, false);
        $list  = [];
        $minId = 2;
        if ($res['msg'] == 'SUCCESS' || $res['msg'] == '获取数据成功') {
            $list = $this->fqcat($res['data']);
            if (isset($res['min_id'])) {
                $minId = $res['min_id'];
            }
        }
        //判断已导入
        if ($list) {
            $ids = [];
//            $redis = $this->redis;
//            $key   = 'Zhan_nei_goods_item_ids';
//            $value = $redis->get($key);
//            if ($value) {
//                $ids = json_decode($value, true);
//            } else {
            $ids = (new Goods())->goods_all_item_id()->toarray();
            if ($ids) {
                $ids = array_column($ids, 'item_id');
//                    $redis->set($key, json_encode($ids), 300);
            }
//            }
            foreach ($list as &$v) {
                $v['imported'] = in_array($v['itemid'], $ids) ? 1 : 0;
            }
        }

        $paginator               = new PaginatorArray(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items              = $paginator->getPaginate();
        $list_items->total_items = 10000;
        $list_items->min_id      = $minId;
        if ($page > 1) {
            $list_items->items = $list;
        }
        $this->ok($list_items);
    }

    /**
     * 商品商品类目
     */
    private function fqcat($data)
    {

        foreach ($data as &$v) {
            $v['fqcat'] = isset($this->classify[$v['fqcat']]) ? $this->classify[$v['fqcat']] : '';
        }
        return $data;
    }

    /**
     * 站内商品列表
     */
    public function znlistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $this->params['limit'] = 10;
        }
        $goods = new Goods();
        $count = $goods->goods_count($this->params);
        $list  = [];
        if ($count) {
            $list = $goods->goods_list($this->params)->toarray();
        }
        $result = ToolsController::paging($list, $count, $this->params['limit'], $this->params['page']);

        $this->ok($result);
    }

    /**
     * 站内商品置顶
     */
    public function ztopAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        if (!isset($this->params['top'])) {
            $this->fail(-1, 'top不能为空');
        }
        $top   = intval($this->params['top']);
        $id    = trim($this->params['id']);
        $ids   = explode(',', $id);
        $goods = new Goods();
        if (count($ids) > 1) {
            $result = $goods->find(['id In (' . $id . ')'])->update([
                'top'        => $top,
                'updated_at' => date('Y-m-d H:i:s', time())
            ]);
//            var_dump($result);exit;
        } else {
            $exist = $goods->goods_detail($id, true);
            if (empty($exist)) {
                $this->fail(-1, '站内商品不存在');
            }
            $exist->top        = $top;
            $exist->updated_at = date('Y-m-d H:i:s', time());
            $result            = $exist->save();
            if ($result === false) {
                $messages = $exist->getMessages();
                foreach ($messages as $message) {
                    echo $message, "\n";
                }
                exit;
            }
        }


        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    /**
     * 删除站内商品
     */
    public function zdeleteAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $id     = trim($this->params['id']);
        $goods  = new Goods();
        $result = $goods->find(['id In (' . $id . ')'])->delete();
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '删除失败');
        }

    }

    /**
     * 站内商品上线
     */
    public function zstatusAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        if (!isset($this->params['status'])) {
            $this->fail(-1, 'status不能为空');
        }
        $status = intval($this->params['status']);
        $id     = trim($this->params['id']);
        $ids    = explode(',', $id);
        $goods  = new Goods();
        if (count($ids) > 1) {
            $result = $goods->find(['id In (' . $id . ')'])->update([
                'status'     => $status,
                'updated_at' => date('Y-m-d H:i:s', time())
            ]);
//            var_dump($result);exit;
        } else {
            $exist = $goods->goods_detail($id, true);
            if (empty($exist)) {
                $this->fail(-1, '站内商品不存在');
            }
            $exist->status     = $status;
            $exist->updated_at = date('Y-m-d H:i:s', time());
            $result            = $exist->save();
            if ($result === false) {
                $messages = $exist->getMessages();
                foreach ($messages as $message) {
                    echo $message, "\n";
                }
                exit;
            }
        }


        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    /**
     * 好裆裤分类
     */
    public function zcateAction()
    {

        $list = [];
        foreach ($this->classify as $k => $v) {
            $list[] = [
                'id'   => $k,
                'name' => $v
            ];
        }
        $this->ok($list);
    }


    protected function zadd($id, $data)
    {
        $result = false;
        $goods  = new Goods();
        $count  = $goods->goods_count_by(['item_id =' . $id]);
        if ($count) {
            $this->fail(-1, '已存在商品');
        }

        /**
         * @see Haodanku::h_goods_detail
         */
        $res = $this->haodanku->h_goods_detail($id);
        if ($res) {
            $goods->created_at         = date('Y-m-d H:i:s', time());
            $goods->item_id            = $res['itemid'];
            $goods->category_id        = $data['category_id'];
            $goods->category_second_id = $data['category_second_id'];
            $goods->column_id          = $data['column_id'];
            $goods->column_second_id   = $data['column_second_id'];
            $goods->title              = $res['itemtitle'];
            $goods->short_title        = $res['itemshorttitle'];
            $goods->shop_type          = $res["shoptype"] == "B" ? "天猫" : "淘宝";
            $goods->pic_logo           = $res['itempic'];
            $goods->coupon_money       = $res['couponmoney'];
            $goods->price              = $res['itemprice'];
            $goods->end_price          = $res['itemendprice'];
            $goods->month_sale         = $res['itemsale'];
            $goods->shop_name          = $res['shopname'];
            $goods->commission         = $res['tkmoney'];
            $goods->coupon_surplus     = $res['couponsurplus'];
            $goods->site               = 'haodanku';
            $goods->status             = 1;
            $result                    = $goods->save();
        }
        return $result;
    }

    /**
     * 站内商品修改/添加
     */
    public function zupdateAction()
    {
        $result                     = false;
        $id                         = isset($this->params['id']) ? trim($this->params['id']) : '';
        $data['category_id']        = isset($this->params['category_id']) ? intval($this->params['category_id']) : 0;
        $data['category_second_id'] = isset($this->params['category_second_id']) ? intval($this->params['category_second_id']) : 0;
        $data['column_id']          = isset($this->params['column_id']) ? strstr($this->params['column_id'], '_', true) : 0;
        $data['column_second_id']   = isset($this->params['column_second_id']) ? strstr($this->params['column_second_id'], '_', true) : 0;
        if ((empty($data['category_id']) && empty($data['category_second_id'])) && (empty($data['column_id']) && empty($data['column_second_id']))) {
            $this->fail(-1, '商品分类/栏目不能都为空');
        }

        if (empty($id)) {//添加
            $item_id = isset($this->params['item_id']) ? trim($this->params['item_id']) : '';
            if (empty($item_id)) {
                $this->fail(-1, '商品ID不能都为空');
            }
            $result = $this->zadd($item_id, $data);
        } else {//修改
            $goods = new Goods();
            $ids   = explode(',', $id);
            if (count($ids) > 1) {
                $data['column_second_id'] = date('Y-m-d H:i:s', time());
                $result                   = $goods->find(['id In (' . $id . ')'])->update($data);
//            var_dump($result);exit;
            } else {
                $exist = $goods->goods_detail($id, true);
                if (empty($exist)) {
                    $this->fail(-1, '站内商品不存在');
                }
                $exist->category_id        = $data['category_id'];
                $exist->category_second_id = $data['category_second_id'];
                $exist->column_id          = $data['column_id'];
                $exist->column_second_id   = $data['column_second_id'];
                $exist->updated_at         = date('Y-m-d H:i:s', time());
                $result                    = $exist->save();
            }
        }

        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    /**
     * 站内商品栏目列表
     */
    public function clistAction()
    {
        $model      = new GoodsColumn();
        $categories = new Category();
        $tree       = new Tree();
        $list       = $model->goods_column_all()->toarray();
        foreach ($list as &$v) {
            $v['api_switch'] = $v['api_switch'] ? true : false;
        }
        $mytree = $tree->array2tree($list, 'name', 'id', 'parent_id');
//        $mytree = $tree->list2tree($list, 'id', 'parent_id', 'children');
//        $test   = [];
//        foreach ($mytree as $v) {
//            $item = [
//                'column_id' => $v['id'],
//                'name'      => $v['name'],
//                'children'  => []
//            ];
//            foreach ($v['children'] as $vv) {
//                $children['column_second_id'] = $vv['value'];
//                $children['name']             = $vv['name'];
//                $key                          = 'down';
//                if ($vv['icon']) {
//                    $children['icon'] = $vv['icon'];
//                    $key              = 'up';
//                }
//                $item['children'][$key][] = $children;
//                unset($children['icon']);
//            }
//            $test[] = $item;
//        }
//        $this->ok($test);

        $res                  = $categories->goods_categories_all()->toarray();
        $result['column']     = $mytree;
        $result['categories'] = $tree->array2tree($res, 'name', 'id', 'parent_id');

        $this->ok($result);
    }


    /**
     * 修改栏目
     */
    public function cupdateAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '栏目分类id不能为空');
        }
        $collegeColumn = new GoodsColumn();
        $info          = $collegeColumn->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该记录不存在，或已被删除');
        }
        $this->column_validate_field($this->params);
        $info['name']       = trim($this->params['name']);
        $info['parent_id']  = intval($this->params['parent_id']);
        $info['updated_at'] = date('Y-m-d H:i:s');
        if ($this->params['icon']) {
            $info['icon'] = trim($this->params['icon']);
        }
//        $info['created_at'] = date('Y-m-d H:i:s');
        if ($info['parent_id'] && isset($this->params['value'])) {
            $info['value'] = trim($this->params['value']);
        }
        $save_column = new GoodsColumn();
        $result      = $save_column->save_cloumn($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '操作失败');
        }
    }

    /**
     * 栏目api 开关
     */
    public function cswitchAction()
    {
        if (!isset($this->params['id'])) {
            $this->fail(-1, '栏目分类id不能为空');// value
        }
        $parent_id     = isset($this->params['parent_id']) ? $this->params['parent_id'] : 0;
        $collegeColumn = new GoodsColumn();
        $info          = $collegeColumn->find_by($parent_id, $this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该记录不存在，或已被删除');
        }
        $info['api_switch'] = isset($this->params['api_switch']) ? intval($this->params['api_switch']) : 0;
        $info['updated_at'] = date('Y-m-d H:i:s');
        $save_column        = new GoodsColumn();
        $result             = $save_column->save_cloumn($info);
        if ($result) {
            $redis = $this->getRedis();
            $key   = 'Goods_column_api_switch_' . $parent_id . '_second_' . trim($this->params['id']);
            $redis->set($key, $info['api_switch']);
            $this->ok([]);
        } else {
            $this->fail(-1, '操作失败');
        }
    }

    /**
     * 添加栏目
     */
    public function caddAction()
    {
        $this->column_validate_field($this->params);
        $info['name']      = trim($this->params['name']);
        $info['parent_id'] = intval($this->params['parent_id']);
//        $info['updated_at'] = date('Y-m-d H:i:s');
        $info['created_at'] = date('Y-m-d H:i:s');
        if ($info['parent_id'] > 0 && isset($this->params['value'])) {
            $info['value'] = intval($this->params['value']);
        }
        if ($this->params['icon']) {
            $info['icon'] = trim($this->params['icon']);
        }
        $model  = new GoodsColumn();
        $result = $model->save_cloumn($info);

        if ($result) {
            if (!$info['parent_id']) {
                $goods        = $model->findFirst('id=' . $model->id);
                $goods->value = $model->id;
                $goods->update();
            }
            $this->ok([]);
        } else {
            $this->fail(-1, '操作失败');
        }
    }

    /**
     * 获取栏目父级
     */
    public function cparentAction()
    {

        $model  = new GoodsColumn();
        $result = $model->goods_column_parents();
        if ($result) {
            $this->ok($result);
        } else {
            $this->fail(-1, '操作失败');
        }
    }

    private function column_validate_field($params)
    {
        if (!isset($params['name']) || empty($params['name'])) {
            $this->fail(-1, '栏目分类名称不能为空');
        }
        if (!isset($params['parent_id'])) {
            $this->fail(-1, '父级不能为空');
        }
    }

    /**
     * 删除站内商品栏目
     */
    public function cdeleteAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '栏目id不能为空');
        }
        $model = new GoodsColumn();
        $info  = $model->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该记录不存在，或已被删除');
        }
        if (empty($info['parent_id'])) {// 顶级
            $child = $model->find_by_parent_id($info['id']);
            if ($child) {
                $this->fail(-1, '该栏目下面有子栏目，不能删除');
            }
        } else { // 二级
            $count = (new Goods())->goods_count_by(['column_second_id =' . $info['value']]);
            if ($count) {
                $this->fail(-1, '该栏目下面有商品，不能删除');
            }
        }
        $result = $model->findFirstById($this->params['id'])->delete();
        if ($result) {
            $redis = $this->getRedis();
            $key   = 'Goods_column_api_switch_' . $info['parent_id'] . '_second_' . $info['value'];
            $redis->del($key);
            $this->ok([]);
        } else {
            $this->fail(-1, '操作失败');
        }
    }

    /**
     * 站内商品栏目和分类
     */
    public function columncateAction()
    {
        $model      = new GoodsColumn();
        $categories = new Category();
        $tree       = new Tree();
        $list       = $model->goods_column_all('id,value,name as label,parent_id')->toarray();
        foreach ($list as &$v) {
            $v['value'] .= '_' . uniqid();
        }
        $res                = $categories->goods_categories_all('id as value,name as label,parent_id')->toarray();
        $data['column']     = $tree->list2tree($list, 'id', 'parent_id', 'children');
        $data['categories'] = $tree->list2tree($res, 'value', 'parent_id', 'children');

        $this->ok($data);
    }

    /**
     * 查询商品详情
     */
    public function detailsAction()
    {
        if (!isset($this->params['item_id']) || empty($this->params['item_id'])) {
            $this->fail(-1, '商品id不能为空');
        }

        $where = 'status =1 and item_id =' . intval($this->params['item_id']);
        if (isset($this->params['column_id'])) {
            $where .= ' and column_id =' . strstr($this->params['column_id'], '_', true);
        }
        if (isset($this->params['column_second_id'])) {
            $where .= ' and column_second_id =' . strstr($this->params['column_second_id'], '_', true);
        }
        if (isset($this->params['category_id'])) {
            $where .= ' and category_id =' . intval($this->params['category_id']);
        }
        if (isset($this->params['category_second_id'])) {
            $where .= ' and category_second_id =' . intval($this->params['category_second_id']);
        }

        $result = (new Goods())->goods_details($where);

        if ($result) {
            $this->ok($result->toarray());
        } else {
            $this->fail(-1, '商品查询失败');
        }
    }


    /**
     * 查询广告详情
     */
    public function adetailsAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '商品id不能为空');
        }
        $where  = 'id =' . intval($this->params['id']);
        $result = (new GoodsAdvertising())->goods_advertising_details($where);
        if ($result) {
            $this->ok($result->toarray());
        } else {
            $this->fail(-1, '查询广告失败');
        }
    }

    /**
     *     设置栏目/分类 对应推广 商品/广告
     */
    public function generalizeAction()
    {
        if (!isset($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $id    = trim($this->params['id']);
        $redis = $this->getRedis();
        if (isset($this->params['is_column']) && $this->params['is_column'] == 1) {
            $parent_id = trim($this->params['parent_id']);
            $key       = 'Generalize_column_' . $parent_id . '_second_' . $id;
        } else {
            $key = 'Generalize_categories_' . $id;
        }

        if ($this->request->isGet()) {//获取
            $res    = $redis->get($key);
            $result = empty($res) ? [] : json_decode($res, true);
            $this->ok($result);
        } else {//设置
            if (!isset($this->params['data'])) {
                $this->fail(-1, '参数有误！');
            }
            $value = trim($this->params['data']);
            if (empty(json_decode($value, true))) {
                $result = $redis->del($key);
            } else {
                $result = $redis->set($key, $value);
            }
            if ($result) {
                $this->ok([]);
            } else {
                $this->fail(-1, '设置失败');
            }
        }

    }

    /**
     *     获取分类对应商品
     */
    public function categorygoodsAction()
    {
//        if (empty($this->params['category_id']) && empty($this->params['category_second_id']) && empty($this->params['column_second_id'])) {
//            $this->fail(-1, '参数有误');
//        }
        $where = '';
        if (isset($this->params['category_id']) && $this->params['category_id'] > 0) {
            $where = 'category_id =' . intval($this->params['category_id']);
        }
        if (isset($this->params['category_second_id']) && $this->params['category_second_id'] > 0) {
            $where = ' category_second_id =' . intval($this->params['category_second_id']);
        }
        if (isset($this->params['column_id']) && $this->params['column_id'] > 0) {
            $where = 'column_id =' . intval($this->params['column_id']);
        }
        if (isset($this->params['column_second_id'])) {
            $where = ' column_second_id =' . intval($this->params['column_second_id']);
        }

        $result = (new Goods())->goods_all_by([$where]);

        if ($result) {
            $this->ok($result->toarray());
        } else {
            $this->fail(-1, '商品查询失败');
        }
    }

    /**
     *     获取全部商品广告
     */
    public function alladvertisingAction()
    {
        $result = (new GoodsAdvertising())->goods_advertising_all();
        if ($result) {
            $this->ok($result->toarray());
        } else {
            $this->fail(-1, '商品查询失败');
        }
    }

    /**
     *   广告列表
     */
    public function alistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $this->params['limit'] = 10;
        }
        $model = new GoodsAdvertising();
        $count = $model->goods_advertising_count($this->params);
        $list  = [];
        if ($count) {
            $list = $model->goods_advertising_list($this->params)->toarray();
        }
        $result = ToolsController::paging($list, $count, $this->params['limit'], $this->params['page']);

        $this->ok($result);
    }

    /**
     *   添加广告
     */
    public function aaddAction()
    {
        $model  = new GoodsAdvertising();
        $result = $model->save_params($this->params);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '添加失败');
        }
    }

    /**
     *   编辑广告
     */
    public function aupdateAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $model = new GoodsAdvertising();
        $exist = $model->find_by_id($this->params['id'], true);
        if (empty($exist)) {
            $this->fail(-1, '广告不存在');
        }
        $exist->name          = $this->params['name'];
        $exist->path          = $this->params['path'];
        $exist->app_path      = $this->params['app_path'];
        $exist->type          = $this->params['type'];
        $exist->url           = $this->params['url'];
        $exist->app_data      = $this->params['app_data'];
        $exist->is_tb_atuh    = intval($this->params['is_tb_atuh']);
        $exist->is_need_login = intval($this->params['is_need_login']);
        $exist->relationId    = intval($this->params['relationId']);
        $result               = $exist->save();
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail('修改失败');
        }
    }

    /**
     *   删除广告
     */
    public function adeleteAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $id     = trim($this->params['id']);
        $model  = new GoodsAdvertising();
        $result = $model->find(['id In (' . $id . ')'])->delete();
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '删除失败');
        }
    }


    /**
     * redis
     */
    private function getRedis()
    {
        $redis = $this->redis;

        return $redis;
    }

}
